<template>
  <div class="chat-container">
    <van-nav-bar :title="name" style="height: 20px"/>
    <div class="messages" ref="messagesContainer">
      <div v-for="msg in messages" :key="msg.id" :class="{'my-message': msg.own, 'other-message': !msg.own}">
        <van-image :src="msg.avatar" width="40px" height="40px" />
        <span>{{ msg.username }}: {{ msg.content }}</span>
      </div>
    </div>
    <van-cell-group>
      <van-field
          v-model="message"
          label="消息"
          placeholder="输入消息"
          type="text"
          :rows="1"
          autosize
      />
    </van-cell-group>
    <van-button type="primary" @click="sendMessage">发送</van-button>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import {useUserStore} from "../../stores";
import {useRoute, useRouter} from "vue-router";

const message = ref('');
const messages = ref<{ id: number, type: number, content: string, own: boolean, username: string, avatar: string, from: string, to: string }[]>([]);
let messageId = 0;
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const name = route.query.username;
 let websocket: WebSocket | null = null;
const sendMessage = () => {
  if (message.value.trim() && websocket) {
    const msg = { content: message.value,type: 3, username: userStore.currentLoginUserInfo.username || "佚名", avatar: userStore.currentLoginUserInfo.avatarUrl || "https://img2.baidu.com/it/u=2731456700,436164171&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500", from: userStore.currentLoginUserInfo.id + "", to: route.query.userId + ""};
    // webSocket的send方法，用于将消息发送到服务器
    websocket.send(JSON.stringify(msg));
    // 将消息显示在页面
    messages.value.push({ ...msg, id: messageId++, own: true });
    message.value = ''; // 清空输入框
    // 将消息存入本地储存
    window.localStorage.setItem("chat_msg_list_" + route.query.userId, JSON.stringify(messages.value))
  }
};

//连接websocket
const connectWebSocket = () => {
  websocket = new WebSocket("ws://175.178.127.190:8889/ws");
  // 服务器发送信息到客户端会触发该方法
  websocket.onmessage = (event) => {
    //这里是心跳
    if (event.data == "heartbeat") {
      // 如果后端返回心跳，就清除定时关闭连接
      clearTimeout(closeConnectTime);
      closeConnect();
      return;
    }
    /*//这里是挤下线
    let shutdown = JSON.parse(event.data);
    if (shutdown.type == 6) {
      //挤下线，跳到登录页面
      router.replace("/user/login")
      showToast("你的账号已在其它设备登录，若非本人操作，请修改密码！")
    }*/
    const data = JSON.parse(event.data);
    messages.value.push({ id: messageId++, type: 3, content: data.content, own: false, username: data.username || "佚名", avatar: data.avatar || "https://img2.baidu.com/it/u=2731456700,436164171&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500", from: data.from, to: data.to });
    // 将消息存入本地储存
    window.localStorage.setItem("chat_msg_list_" + route.query.userId, JSON.stringify(messages.value))
  };
  // 成功连接后触发
  websocket.onopen = () => {
    // 客户端连接服务端成功后，就开始发送心跳
    sendHeard();
    // 关闭连接
    closeConnect()
  }
  // websocket 关闭后
  websocket.onclose = () => {
    // 关闭连接时， 清除定时发送心跳的任务
    clearInterval(sendHeardTime);
    // 客户端断开连接
    messages.value.push({ id: messageId++, type: 3, content: "客户端断开连接", own: false, username: "服务器", avatar: "https://img0.baidu.com/it/u=819497721,3608085387&fm=253&fmt=auto&app=138&f=JPEG?w=569&h=313", from: "no", to: "no" });
  }
};
onMounted(() => {
  connectWebSocket();
  if (window.localStorage.getItem("chat_msg_list_" + route.query.userId)) {
    messages.value = JSON.parse(window.localStorage.getItem("chat_msg_list_" + route.query.userId) as string);
  }
})

/*// 页面关闭时，如果websocket还存在，就关闭。  应该是用户完全退出应用才关闭
onUnmounted(() => {
  if (websocket) {
    //服务器关闭会触发该方法
    websocket.close();
  }
})*/

// 与服务器建立连接的函数
setTimeout(function () {
  const msg = {type: 1, from: userStore.currentLoginUserInfo.id + ""};
  //等待websocket连接建立完成，然后发送消息
  websocket?.send(JSON.stringify(msg));
}, 1000);
// 5s 发送一个心跳
let sendHeardTime: number;
const sendHeard = () => {
  sendHeardTime = setInterval(() => {
    websocket?.send(JSON.stringify({type: 2}))
  }, 5000)
}
// 关闭websocket连接的函数
let closeConnectTime: number;
const closeConnect = () => {
  closeConnectTime = setTimeout(() => {
    websocket?.close();
  }, 10000);
}
</script>

<style scoped>
.chat-container {
  padding: 20px;
}

.messages {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  height: 300px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.my-message {
  margin-bottom: 10px;
  background-color: #dcf8c6;
  padding: 10px;
  border-radius: 5px;
  display: flex;
  align-items: center;
}

.other-message {
  margin-bottom: 10px;
  background-color: #f3f3f3;
  padding: 10px;
  border-radius: 5px;
  display: flex;
  align-items: center;
}
</style>
